class AudioProcessor extends AudioWorkletProcessor {
  constructor() {
    super();
    this.samples = [];
    this.port.onmessage = (e) => {
      if (e.data === 'flush') {
        this.flush();
      }
    };
  }

  process(inputs) {
    const input = inputs[0];
    if (input && input[0]) {
      this.samples.push(...input[0]);
    }
    return true;
  }

  flush() {
    if (this.samples.length > 0) {
      const int16Samples = new Int16Array(
        this.samples.map(s => Math.max(-1, Math.min(1, s))).map(s => s * 32767)
      )
      this.port.postMessage(int16Samples);
      this.samples = [];
    }
  }
}



registerProcessor('audio-processor', AudioProcessor);
